#include "tokenfile.h"

#include <QDir>
#include <QMessageBox>

TokenFile::TokenFile()
    : filePath()
    , file()
{}

QString TokenFile::write(const TokenList &list, QByteArray fileName)
{
    filePath = fileName;
    file.setFileName(filePath);
    if(!file.open(QIODevice::WriteOnly)) {
        QMessageBox::critical(nullptr,"错误",QString("%1只写打开失败").arg(filePath));
        return "";
    }
    auto str = GetDir(filePath);
    op.setDevice(&file);
    op << TokenList_to_FileData(list);
    file.close();
    return str;
}

QString TokenFile::read(TokenList &list, QByteArray fileName)
{
    filePath = fileName;
    file.setFileName(filePath);
    if(!file.open(QIODevice::ReadOnly)) {
        QMessageBox::critical(nullptr,"错误",QString("%1只读打开失败").arg(filePath));
        return "";
    }
    auto str = GetDir(filePath);
    op.setDevice(&file);
    list = FileData_to_TokenList(op.readAll());
    file.close();
    return str;
}

QString TokenFile::TokenList_to_FileData(const TokenList &list)
{
    QStringList strList;
    strList.push_back("行号\t单词内容\t单词类型");
    foreach(const auto& tok, list) {
        if(tok.second.GetVariety() >= _blank) {
            continue;
        }
        QStringList str{QString::number(tok.first),tok.second.GetContent(),tok.second.GetVarietyString_cn()};
        auto line = str.join("\t");
        strList.push_back(line);
    }
    return strList.join("\n");
}

TokenList TokenFile::FileData_to_TokenList(const QString &str)
{
    TokenList list;
    auto strList = str.split("\n");
    if(strList[0] == "行号\t单词内容\t单词类型") {
        strList.erase(strList.cbegin());
    }
    foreach (const auto& str, strList) {
        auto data = str.split("\t");
        list.push_back(Token(data[0].toInt(),Word(Word::String_cnToVariety(data[2]),data[1])));
    }
    return list;
}

QString TokenFile::GetDir(QByteArray fileName)
{
    // 获取应用程序的当前工作目录
    QString currentPath = QDir::currentPath();

    // 构建绝对路径
    QString absolutePath = QDir(currentPath).filePath(fileName);

    // 使用QFileInfo获取文件的绝对路径
    return QFileInfo(absolutePath).absoluteFilePath();
}
